import { testConnection, closePool } from '../config/database';
import { testRedisConnection, closeRedis, getRedisClient } from '../config/redis';
import { CacheStrategies } from './cache';
import { initializeSchemaService } from '../services/schemaService';

// 数据库初始化类
export class DatabaseInitializer {
  // 测试所有数据库连接
  static async testConnections(): Promise<boolean> {
    console.log('Testing database connections...');

    try {
      // 测试PostgreSQL连接
      const pgConnected = await testConnection();
      if (!pgConnected) {
        console.error('PostgreSQL connection failed');
        return false;
      }

      // 测试Redis连接
      const redisConnected = await testRedisConnection();
      if (!redisConnected) {
        console.error('Redis connection failed');
        return false;
      }

      // 初始化schema服务
      const redisClient = getRedisClient();
      initializeSchemaService(redisClient);
      console.log('Schema service initialized');

      console.log('All database connections successful');
      return true;
    } catch (error) {
      console.error('Database connection test failed:', error);
      return false;
    }
  }

  // 初始化数据库（运行迁移和种子数据）
  static async initialize(): Promise<boolean> {
    console.log('Initializing database...');

    try {
      // 首先测试连接
      const connected = await this.testConnections();
      if (!connected) {
        return false;
      }

      // 运行数据库迁移
      await this.runMigrations();

      // 运行种子数据
      await this.runSeeds();

      // 预热缓存
      await CacheStrategies.warmupCache();

      console.log('Database initialization completed successfully');
      return true;
    } catch (error) {
      console.error('Database initialization failed:', error);
      return false;
    }
  }

  // 运行数据库迁移
  private static async runMigrations(): Promise<void> {
    console.log('Running database migrations...');

    // 这里可以添加迁移逻辑
    // 在实际项目中，可能会使用专门的迁移工具如 node-pg-migrate

    console.log('Database migrations completed');
  }

  // 运行种子数据
  private static async runSeeds(): Promise<void> {
    console.log('Running database seeds...');

    // 这里可以添加种子数据逻辑
    // 在开发环境中可以自动运行种子数据

    console.log('Database seeds completed');
  }

  // 优雅关闭所有数据库连接
  static async shutdown(): Promise<void> {
    console.log('Shutting down database connections...');

    try {
      await Promise.all([
        closePool(),
        closeRedis()
      ]);

      console.log('Database connections closed successfully');
    } catch (error) {
      console.error('Error during database shutdown:', error);
    }
  }

  // 健康检查
  static async healthCheck(): Promise<{
    postgresql: boolean;
    redis: boolean;
    overall: boolean;
  }> {
    const postgresql = await testConnection();
    const redis = await testRedisConnection();

    return {
      postgresql,
      redis,
      overall: postgresql && redis
    };
  }
}

// 导出初始化函数
export const initializeDatabase = DatabaseInitializer.initialize;
export const testDatabaseConnections = DatabaseInitializer.testConnections;
export const shutdownDatabase = DatabaseInitializer.shutdown;
export const databaseHealthCheck = DatabaseInitializer.healthCheck;